package com.demo.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.demo.dao.TableJnlnoMapper;
import com.demo.service.TableJnlnoService;

@Service
public class TableJnlnoServiceImpl implements TableJnlnoService{
	
	@Autowired
	private TableJnlnoMapper tableJnlnoMapper ;
	
	@Override
	public Long queryJnlno(String jnlType) {
		return this.tableJnlnoMapper.selectJnlno(jnlType);
	}

	@Override
	public void updateJnlno(Map map) {
		this.tableJnlnoMapper.updateJnlno(map);
	}
	
	// 【注】select for update 和 update 必须在同一个事务中，才能真正确保多个服务之间互斥
	@Transactional	
	@Override
	public Long getNextIdFromDb(String jnlType, long maxId, int step) {
		Long currentId ;
		// 根据jnlType，查询当前序号值
		currentId = this.queryJnlno(jnlType) ;
		if(null == currentId) {
			throw new RuntimeException("fatal error in TableIdFactory, please init the type("+ jnlType +")") ;
		}
		
		// 若最大缓存值超出最大限值，则回滚currentId和maxCacheId
		Long maxCacheId = currentId + step ;
		if(maxCacheId >= maxId) {
			currentId = 1L ;
			maxCacheId = currentId + step ;
		}
		// 更新最大缓存值到数据库中
		Map param = new HashMap() ;
		param.put("jnlType", jnlType) ;
		param.put("jnlNo", maxCacheId) ;
		this.updateJnlno(param);
		
		return currentId ;
	}

}
